﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SWS.PIP.Label
{
	class CommonFunctions
	{
		/// <summary>
		/// 将LINQ数据转换成DataTable数据，LINQ数据必须包含表头
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="varlist"></param>
		/// <returns></returns>
		public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
		{
			DataTable dtReturn = new DataTable();
			// column names 
			PropertyInfo[] oProps = null;

			if (varlist == null)
				return dtReturn;

			foreach (T rec in varlist)
			{
				if (oProps == null)
				{
					oProps = ((Type)rec.GetType()).GetProperties();
					foreach (PropertyInfo pi in oProps)
					{
						Type colType = pi.PropertyType;

						if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
						{
							colType = colType.GetGenericArguments()[0];
						}

						dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
					}
				}

				DataRow dr = dtReturn.NewRow();

				foreach (PropertyInfo pi in oProps)
				{
					dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);
				}

				dtReturn.Rows.Add(dr);
			}

			return dtReturn;
		}

		/// <summary>
		/// 构建DataTable的字符串数据
		/// </summary>
		/// <param name="oDataTable"></param>
		/// <param name="arrColumnWidth"></param>
		/// <returns></returns>
		public static string GetLeftAlignReportFromDT(DataTable oDataTable, int[] arrColumnWidth)
		{
			string sResult = "";
			if (oDataTable.Rows.Count == 0)
			{
				return sResult;
			}

			if (oDataTable.Columns.Count != arrColumnWidth.Length)
			{
				return "Format datatable fialed. Input datatable's column count is not equal to format array data count.";
			}

			//获取行字符总长度（每个Column后补充iSpaceCount个空格）
			int iRowTotalLen = 1;//换行符占一个
			int iSpaceCount = 2;//每个列数据间空格数量
			for (int i = 0; i < arrColumnWidth.Length; i++)
			{
				iRowTotalLen += (arrColumnWidth[i] + iSpaceCount);
			}

			foreach (DataRow row in oDataTable.Rows)
			{
				//获取数据最大行数，按列宽要求，最大数据行数
				int iMaxLineCount = 0;
				int iTemLineCount = 0;
				string sCurrCellData;
				int iStringLength = 0;
				for (int iCol = 0; iCol < oDataTable.Columns.Count; iCol++)
				{
					sCurrCellData = row[iCol].ToString();
					iStringLength = GetStringLength(sCurrCellData);
					iTemLineCount = (int)Math.Ceiling((double)iStringLength / arrColumnWidth[iCol]);
					if (iTemLineCount > iMaxLineCount)
					{
						iMaxLineCount = iTemLineCount;
					}
				}

				//格式化行数据
				string sBlankString = "";
				int iCurrColumnWidth = 0;
				string[] arrColumnPrestring = new string[arrColumnWidth.Length];//保存已切割字符
				string sTempString = "";
				string sFormatRowString = "";
				for (int iRow = 0; iRow < iMaxLineCount; iRow++)
				{
					int iCurrRowLen = 0;//当前行，到当前列位置，字符的长度
					int iNeedAddSpaceCount = 0;
					for (int iCol = 0; iCol < oDataTable.Columns.Count; iCol++)
					{
						iCurrColumnWidth = arrColumnWidth[iCol];
						sCurrCellData = row[iCol].ToString();
						iStringLength = GetStringLength(sCurrCellData);
						//字符在当前列中无数据
						if (sCurrCellData.Length <= iRow * iCurrColumnWidth)
						{
							sTempString = sBlankString.PadRight(iCurrColumnWidth);
						}
						//字符介于当前列 或 字符超过当前列
						else
						{
							sTempString = GetSubStringByLength(arrColumnPrestring[iCol] == null ? sCurrCellData : sCurrCellData.Replace(arrColumnPrestring[iCol], ""), iCurrColumnWidth);
							arrColumnPrestring[iCol] += sTempString;
						}

						//补空格
						sFormatRowString += sTempString;
						iCurrRowLen += arrColumnWidth[iCol] + iSpaceCount;
						iNeedAddSpaceCount = iRow * iRowTotalLen + iCurrRowLen - GetStringLength(sFormatRowString);
						while (iNeedAddSpaceCount > 0)
						{
							sFormatRowString += " ";
							--iNeedAddSpaceCount;
						}
					}

					sFormatRowString += "\n";
				}

				sResult += sFormatRowString;
			}

			return sResult;
		}

		/// <summary>
		/// 获取字符占位长度（一个中午字符占两个位）
		/// </summary>
		/// <param name="sString"></param>
		/// <returns></returns>
		public static int GetStringLength(string sString)
		{
			if (sString.Length == 0)
			{
				return 0;
			}

			ASCIIEncoding ascii = new ASCIIEncoding();
			byte[] s = ascii.GetBytes(sString);
			int iTempLen = 0;
			for (int i = 0; i < s.Length; i++)
			{
				if ((int)s[i] == 63)
				{
					iTempLen += 2;
				}
				else
				{
					iTempLen += 1;
				}
			}

			return iTempLen;
		}

		/// <summary>
		/// 获取一个指定长度的字符串（一个中午算两个字符长度
		/// </summary>
		/// <param name="sString"></param>
		/// <param name="iLength"></param>
		/// <returns></returns>
		public static string GetSubStringByLength(string sString, int iLength)
		{
			if (sString.Length == 0)
			{
				return sString.PadRight(iLength);
			}

			for (int i = 0; i < sString.Length; i++)
			{
				if (GetStringLength(sString.Substring(0, i + 1)) >= iLength)
				{
					return sString.Substring(0, i + 1);
				}
			}

			return sString.PadRight(iLength - (GetStringLength(sString) - sString.Length));
		}
	}
}
